What if you want to loop through an Associative Array?
You can use FOR EACH to do this task.
Where the WHILE and FOR loops run until an error is encountered, the FOR EACH loop will run through every element in the array.
Let’s revisit the associative array we set up with the trucks...
<?php
$truck[“Toyota”] = Tundra;
$truck[“Nissan”] = Titan;
$truck[“Dodge”] = Ram;
?>
To loop through the Makers / Models, we’d use this code:
<?php
foreach( $truck as $make => $model){
echo "Make: $make, Model: $model <br />";
}
?>
The code is written in a strange way, it isn’t obvious how it works.
Let’s look at it in a simpler way:
$something as $key => $value
FOR each thing in the array, I want to refer to the key as $key and the value as $value.
The operator ‘=>’ indicates the relationship between the key and the value...the key “points” to the value.